package com.redlight.base;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by chao on 2019/1/9.
 */
public class BaseController {
    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    protected final String Ok;
    protected final String Fail;

    public BaseController() {
        this.Ok = ResultStatus.OK.getCode();
        this.Fail = ResultStatus.FAIL.getCode();
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(text == null?null:StringEscapeUtils.escapeHtml4(text.trim()));
            }

            public String getAsText() {
                Object value = this.getValue();
                return value != null?value.toString():"";
            }
        });
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(DateUtil.parseDate(text));
            }
        });
    }

    protected String renderSuccess(HttpServletResponse response, ResultStatus status, Object data, Object... args) {
        return this.renderSuccess(response, status.isSuccess(), status.getCode(), data, args);
    }

    protected String renderSuccess(HttpServletResponse response, boolean flag, String retCode, Object data, Object... args) {
        RestResult result = this.renderResult(flag, retCode, data, args);
        String retJsonStr = JsonUtil.toJson(result);
        return this.renderString(response, retJsonStr, "application/json");
    }

    protected RestResult renderResult(boolean flag, String retCode, Object data, Object... args) {
        return new RestResult(flag, retCode, data, args);
    }

    protected String renderString(HttpServletResponse response, String string, String type) {
        PrintWriter writer = null;

        try {
            if(StringUtils.isBlank(type)) {
                type = "text/plain";
            }

            type = type + "; charset=utf-8";
            response.setHeader("Charset", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType(type);
            writer = response.getWriter();
            writer.write(string);
            writer.flush();
        } catch (IOException var9) {
            var9.printStackTrace();
        } finally {
            if(writer != null) {
                writer.close();
            }

        }

        return null;
    }

    protected HashMap<String, Object> getParameterMap(HttpServletRequest request) {
        HashMap returnMap = new HashMap();
        returnMap.putAll(BaseEntity.newParamMap());
        Map properties = request.getParameterMap();
        Iterator entries = properties.entrySet().iterator();

        while(entries.hasNext()) {
            Entry entry = (Entry)entries.next();
            String name = (String)entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj) {
                returnMap.put(name, "");
            } else {
                if(valueObj instanceof String[]) {
                    String[] values = (String[])((String[])valueObj);
                    if(1 == values.length) {
                        valueObj = values[0];
                    }
                }

                returnMap.put(name, valueObj);
            }
        }

        String paramStr = MapUtil.getString(returnMap, "param");
        Map<String, Object> paraMap = (Map)JSONObject.parseObject(paramStr, Map.class);
        if(null != paraMap) {
            returnMap.putAll(paraMap);
        }

        return returnMap;
    }

    public void addMessage(Object obj, String... messages) {
        int var6;
        if(obj instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest)obj;
            StringBuilder sb = new StringBuilder();
            String[] var5 = messages;
            var6 = messages.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                String message = var5[var7];
                sb.append(message).append(messages.length > 1?"<br/>":"");
            }

            request.setAttribute("message", sb.toString());
        } else {
            StringBuilder sb;
            String[] var10;
            int var11;
            String message;
            if(obj instanceof HttpSession) {
                sb = new StringBuilder();
                var10 = messages;
                var11 = messages.length;

                for(var6 = 0; var6 < var11; ++var6) {
                    message = var10[var6];
                    sb.append(message).append(messages.length > 1?"<br/>":"");
                }

                ((HttpSession)obj).setAttribute("message", sb.toString());
            } else if(obj instanceof RedirectAttributes) {
                sb = new StringBuilder();
                var10 = messages;
                var11 = messages.length;

                for(var6 = 0; var6 < var11; ++var6) {
                    message = var10[var6];
                    sb.append(message).append(messages.length > 1?"<br/>":"");
                }

                ((RedirectAttributes)obj).addFlashAttribute("message", sb.toString());
            } else if(obj instanceof Model) {
                sb = new StringBuilder();
                var10 = messages;
                var11 = messages.length;

                for(var6 = 0; var6 < var11; ++var6) {
                    message = var10[var6];
                    sb.append(message).append(messages.length > 1?"<br/>":"");
                }

                ((ModelMap)obj).addAttribute("message", sb.toString());
            }
        }

    }

    public static void rememberPage(HttpServletRequest request, HttpServletResponse response, Object paraObj) {
        if(null != paraObj) {
            String repage = request.getParameter("repage");
            String no = request.getParameter("page.pageNo");
            if(StringUtils.isNumeric(no)) {
                CookieUtil.setCookie(response, "page.pageNo", no);
            } else if(repage != null) {
                no = CookieUtil.getCookie(request, "page.pageNo");
                if(StringUtils.isNumeric(no)) {
                    if(paraObj instanceof Map) {
                        ((Map)paraObj).put("page.pageNo", no);
                    } else if(paraObj instanceof BaseEntity) {
                        ((BaseEntity)paraObj).getPage().setPageNo(Integer.parseInt(no));
                    }
                }
            }

            String size = request.getParameter("page.pageSize");
            if(StringUtils.isNumeric(size)) {
                CookieUtil.setCookie(response, "page.pageSize", size);
            } else if(repage != null) {
                size = CookieUtil.getCookie(request, "page.pageSize");
                if(StringUtils.isNumeric(size)) {
                    if(paraObj instanceof Map) {
                        ((Map)paraObj).put("page.pageSize", size);
                    } else if(paraObj instanceof BaseEntity) {
                        ((BaseEntity)paraObj).getPage().setPageSize(Integer.parseInt(size));
                    }
                }
            }

            String orderBy = request.getParameter("page.orderBy");
            if(StringUtils.isNotBlank(orderBy)) {
                CookieUtil.setCookie(response, "page.orderBy", orderBy);
            } else if(repage != null) {
                if(paraObj instanceof Map) {
                    ((Map)paraObj).put("page.orderBy", orderBy);
                } else if(paraObj instanceof BaseEntity) {
                    ((BaseEntity)paraObj).getPage().setOrderBy(orderBy);
                }
            }

        }
    }
}
